import express from 'express'
var router = express.Router()
import {getResult,listSql, addSql, putSql, detailSql, deleteSql, countSql, multiDeleteSql} from '../../util/operateSql.js'

const Table1 = 'dicts'
const Table2 = 'dict_items'

router.get('/type/list',async (req,res,next) => {
  const {dict_type,dict_name} = req.query
  const sql = listSql(Table1,{dict_type,dict_name},{hasPage: false,operate: 'like'})
  console.log('sql: ', sql);
  const sql2 = countSql(Table1,{dict_type,dict_name},{hasPage: false,operate: 'like'})
  const rows1 = await getResult(sql)
  const rows2 = await getResult(sql2)
  res.json(req.app.locals.success({list: rows1,total: rows2[0].count}))
})

router.post('/type/add',async (req,res,next) => {
  const {dict_type,dict_name,remark} = req.body
  const sql = addSql(Table1,{dict_type,dict_name,remark})
  const rows1 = await getResult(sql)
  res.json(req.app.locals.success('新增成功'))
})
router.post('/type/update',async (req,res,next) => {
  const {dict_type,dict_name,remark} = req.body
  const sql = putSql(Table1,{dict_name,remark},{dict_type})
  const rows1 = await getResult(sql)
  res.json(req.app.locals.success('新增成功'))
})

// 获取字典数据
router.get('/type/data/query',async (req,res,next) => {
  const { dict_type } = req.query
  const sql = listSql(Table2, {parent_type: dict_type})
  const sql2 = countSql(Table2, {parent_type: dict_type})
  const rows = await getResult(sql)
  const rows2 = await getResult(sql2)
  res.json(req.app.locals.success({list: rows,total: rows2[0].count}))
})
// 新增字典数据
router.post('/type/data/add',async (req,res,next) => {
  const { dict_data_name,dict_data_value,tag_theme,tag_type,tag_class,parent_type } = req.body
  const sql = addSql(Table2, {parent_type,dict_data_name,dict_data_value,tag_theme,tag_type,tag_class})
  console.log('sql: ', sql);
  const rows = await getResult(sql)
  res.json(req.app.locals.success('新增成功'))
})
// 修改字典数据
router.post('/type/data/update',async (req,res,next) => {
  const { dict_data_name,dict_data_value,tag_theme,tag_type,tag_class,parent_type,id } = req.body
  const sql = putSql(Table2, {parent_type,dict_data_name,dict_data_value,tag_theme,tag_type,tag_class},{id})
  const rows = await getResult(sql)
  res.json(req.app.locals.success('修改成功'))
})
// 删除字典数据
router.post('/type/data/del',async (req,res,next) => {
  const {dict_type:parent_type} = req.query
  const { ids } = req.body
  const sql = multiDeleteSql(Table2,{ids})
  await getResult(sql)
  res.json(req.app.locals.success({list: rows,total: rows2[0].count}))
})

export default router